using MediatR;
using Microsoft.AspNetCore.Mvc;
using RBAC_Class.Write.API.Application.Command.Users;
using RBAC_Class.API.Dto;
using RBAC_Class.ErrorCode;
using System;
using System.Threading.Tasks;
using NLog;

namespace RBAC_Class.Write.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<UserController> logger;
        
        public UserController(IMediator mediator, ILogger<UserController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }

        [HttpPost]
        public async Task<APIResult<int>> AddUser(AddUserCommand cmd)
        {
            try
            {
                return await mediator.Send(cmd);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "添加用户失败 - 用户名: {UserName}", cmd.UserName);
                throw;
            }
        }

        [HttpPost]
        public async Task<APIResult<int>> UpdateUser(UpdateUserCommand cmd)
        {
            try
            {
                return await mediator.Send(cmd);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "更新用户失败 - 用户ID: {UserID}, 用户名: {UserName}", cmd.UserID, cmd.UserName);
                throw;
            }
        }

        [HttpPost]
        public async Task<APIResult<int>> DeleteUser(DeleteUserCommand cmd)
        {
            try
            {
                return await mediator.Send(cmd);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "删除用户失败 - 用户ID: {UserID}", cmd.UserID);
                throw;
            }
        }
    }
} 